<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends CommonController
{	
	public $cate;
	public $cate_list;
	
	public function _initialize()
	{
		$this->cate = M('category');
		$this->cate_list = $this->get_lists();
	}

	public function showlist()
	{	
		
		// $result = $this->cate->select();
		// var_dump($this->cate_list);die;
		$this->assign('cate',$this->cate_list);
		$this->display();
	}

	public function append()
	{	


		if(IS_AJAX){
			
			
			if($this->cate->create()){

				if($this->cate->add()){

					$info['code'] = 1;
					$info['info'] = '添加成功';
					$info['status'] = 'success';
					$this->ajaxReturn($info);
				}else{
					$info['code'] = 0;
					$info['info'] = '添加失败';
					$info['status'] = 'error';
					$this->ajaxReturn($info);
				}

			}else{

				$this->ajaxReturn($this->cate->getError());

			}

			$this->ajaxReturn();

			
			

		}
		$this->assign('cate_list',$this->cate_list);
		$this->display();
	}

	public function edit()
	{
		$id=I('id');
		


		$data = $this->cate->where(array('cate_id'=>$id))->field(['catename','pid','cate_id'])->find();
		
		$data['pid'] = (int)$data['pid'];
		
		$this->assign('pid',$data['pid']);
		$this->assign('catename',$data['catename']);
		$this->assign('cate_list',$this->cate_list);

		if(IS_AJAX){
			$cate_id=I('get.id');//获取修改的数据的cate_id

			if($this->cate->create()){
				//父级是此分类时返回错误信息
				if(I('post.pid')==$cate_id){
					$this->ajaxReturn(array('code'=>0,'info'=>'父级有误'));
				}

				//更新数据
				if($this->cate->where(array('cate_id'=>$cate_id))->save()){
					//更新成功
					$this->ajaxReturn(array('code'=>1,'info'=>'修改成功'));
					
				}else{
					//更新失败
					$this->ajaxReturn(array('code'=>0,'info'=>'修改失败'));
					
				}
			}

		}


		$this->display();
	}

	public function del()
	{	
		if(IS_AJAX){
			$cate_id = I('get.id');
			// $data = $this->cate->where(['cate_id'=>$cate_id])->field(['pid'])->find();

			if($subset = $this->cate->where(['pid'=>$cate_id])->select()){

				$this->ajaxReturn(['code'=>0,'info'=>'存在子集无法删除']);
				
			}
			
			if($this->cate->where(array('cate_id'=>$cate_id))->delete()){
				$this->ajaxReturn(['code'=>1,'info'=>'删除成功']);
			}else{
				$this->ajaxReturn(['code'=>0,'info'=>'删除失败']);
			}
		}

	}

	public function get_lists($pid=0,$spac = 0)
	{
		static $data = array();
		$spac += 2;
		$category = M('category');
		$result = $category->where(array(['pid'=>$pid]))->select();
		if($result){
			foreach($result as $val){
				$val['catename'] = str_repeat('&nbsp;&nbsp;',$spac).str_repeat('-',$spac).$val['catename'];
				$data[] = $val;
				$val['data'] = $this->get_lists($val['cate_id'],$spac);

			}
		}
		return $data;
	}
}




?>